#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import xlrd
import shutil
import hashlib

ext = '.xlsx'
export_path = os.path.abspath('..') + "/csv"

def ToString(value):
    return value.encode('utf-8')

def getListFiles(dir):
    ret = []
    for line in os.listdir(dir):
        if os.path.isfile(line):
            info = os.path.splitext(line)
            filename = info[0]
            extension = info[1]
            if extension == ext and filename[0] != '~':
                ret.append(filename)
    return ret

def getFileMd5(name):
    _file = name + ext
    m = hashlib.md5()
    with open(_file, 'rb') as f:
        for line in f:
            m.update(line)
    md5Code = m.hexdigest()
    print (_file, "=>", md5Code  )
    return md5Code

def exportFiles(name):
    _file = name + ext
    print( "export file : " + _file + " start!")
    
    bk = xlrd.open_workbook(_file)
    sh = bk.sheet_by_index(0)
    nrows = sh.nrows
    ncols = sh.ncols
    
    content = ""
    for r in range(0, nrows):
        if r != 2:
            for c in range(0, ncols):
                user = sh.cell_value(2, c)
                if user == "A" or user == "C":
                    val = sh.cell_value(r, c)
                    type_str = sh.cell_value(1, c)
                    if type_str == "number":
                        if type(val) == float:
                            val = int(val)
                        elif val is None:
                            val = -1
                        elif not val.strip():
                            val = -1
                        content += "%s" % val
                    elif type_str == "float":
                        if val is None:
                            val = -1
                        content += "%s" % val
                    else:
                        if type(val) == float:
                            tmp = int(val)
                            if tmp == val:
                                val = tmp
                        content += "%s" % val
                    content += ","
            content = content[:-1]
            content += "\n"
    f = open(export_path + "/" + os.path.splitext(_file)[0] + ".csv", "wb+")
    f.write(ToString(content))
    f.close()

    print ("export file : " + _file + " success!")

if __name__ == '__main__':
    ret = getListFiles(os.path.abspath('.'))
    
    file = export_path + "/md5.csv"
    f = open(file, "wb+")
    content = "name,md5\nstring,string\nname,md5\n"
    for each in ret:
        content += "%s,%s\n" % (each, getFileMd5(each))
        exportFiles(each)
    f.write(ToString(content))
    f.close()
    print ("export files over !!!")
